/*
 * SqliteStore.h
 *
 *  Created on: 2017年3月9日
 *      Author: chuanjiang.zh
 */

#ifndef SQLITESTORE_H_
#define SQLITESTORE_H_

#include "BasicType.h"
#include "sqlite3.h"
#include <string>

class SqliteStore
{
public:
	SqliteStore();
	virtual ~SqliteStore();

	bool open(const std::string& path);

    void close();

    bool isOpen();

    sqlite3* get();


    bool execute(const std::string& sql);

    int queryInt(const std::string& sql, int defValue=0);

	bool queryString(const std::string& sql, std::string& value);

    bool insert(const std::string& sql, int& autoId);

    bool insert(const std::string& sql, int64_t& autoId);


    static int callback(void * /*NotUsed*/, int argc, char **argv, char **azColName);


    template < class T >
    bool queryObject(const std::string& sql, T& t)
    {
    	if (!m_sqlite)
		{
			return false;
		}

		sqlite3_stmt *stmt;
		int rc = sqlite3_prepare_v2(m_sqlite, sql.c_str(), -1, &stmt, NULL);
		if (rc != SQLITE_OK)
		{
			return false;
		}

		bool found = false;
		rc = sqlite3_step(stmt);
		if (rc == SQLITE_ROW)
		{
            //int col = 0;

			found = toObject(stmt, t);
		}

		sqlite3_finalize(stmt);

		return found;
    }


    template < class Container >
    int queryObjects(const std::string& sql, Container& cont)
    {
        if (!m_sqlite)
        {
            return false;
        }

        sqlite3_stmt *stmt;
        int rc = sqlite3_prepare_v2(m_sqlite, sql.c_str(), -1, &stmt, NULL);
        if (rc != SQLITE_OK)
        {
            return false;
        }

        int count = 0;
        for (;;)
        {
            rc = sqlite3_step(stmt);
            if (rc == SQLITE_DONE)
            {
                break;
            }

            if (rc == SQLITE_ROW)
            {
				typename Container::value_type value;
				if (toObject(stmt, value))
				{
					cont.push_back(value);
					count++;
				}
            }
            else
            {
                break;
            }
        }

        sqlite3_finalize(stmt);

        return count;
    }

protected:
	sqlite3*    m_sqlite;

};

#endif /* SQLITESTORE_H_ */
